package com.laycoding.layrpc.handler.client.handler;

import com.laycoding.layrpc.handler.client.LayRpcClientRegistry;
import com.laycoding.layrpc.handler.client.RpcProxyHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class LayRpcClientInitializer extends ChannelInitializer<SocketChannel> {

    private RpcProxyHandler rpcProxyHandler;

    private LayRpcClientRegistry layRpcClientRegistry;

    private ReconnectHandler reconnectHandler;
    public LayRpcClientInitializer(RpcProxyHandler rpcProxyHandler, LayRpcClientRegistry layRpcClientRegistry) {
        this.rpcProxyHandler = rpcProxyHandler;
        this.layRpcClientRegistry = layRpcClientRegistry;
        this.reconnectHandler = new ReconnectHandler(layRpcClientRegistry);
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast("IdleStateTriggerHandler",new IdleStateTriggerHandler());
        pipeline.addLast(new HeartBeatHandler());
        pipeline.addLast(this.reconnectHandler);
        pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
        //自定义协议编码器
        pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
        //对象参数类型编码器
        pipeline.addLast("encoder", new ObjectEncoder());
        //对象参数类型解码器
        pipeline.addLast("decoder", new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
        pipeline.addLast("handler",rpcProxyHandler);
    }
}
